package com.chy.blog_server.core.util;

import cn.hutool.core.util.ObjectUtil;
import com.chy.blog_server.modular.system.entity.SysUser;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 描述：封装session，保存、获取、更新当前登录的用户对象（后台管理用户）
 * 作者：chenhuiyan
 * 时间：2019/9/28 16:40
 */
public class UserUtil {

    /**
     * user在session中的名字，也就是键值对的键。
     */
    public static final String USER_NAME_IN_SESSION = "loginUser";

    /**
     * 获取session 的方法
     * @param request
     * @return
     */
    public static HttpSession getSession(HttpServletRequest request) {
        if(ObjectUtil.isNotEmpty(request)){
            HttpSession session = request.getSession();
            return session;
        }else{
            return null;
        }
    }

    /**
     * 从session中获取到当前用户
     * @param request
     * @return
     */
    public static SysUser getUserFromSession(HttpServletRequest request) {
        HttpSession session = getSession(request);
        if(ObjectUtil.isNotEmpty(session)){
            return (SysUser) session.getAttribute(USER_NAME_IN_SESSION);
        }else{
            return null;
        }
    }

    /**
     * 更新Session中的user
     * @param request
     * @param user
     * @return
     */
    public static SysUser updateUserInSession(HttpServletRequest request, SysUser user) {
        // 直接放入user，顶替掉原来session中的user
        return putUserIntoSession(request, user);
    }

    /**
     * 将user放入Session对象中
     * @param request
     * @param user
     * @return
     */
    public static SysUser putUserIntoSession(HttpServletRequest request, SysUser user) {
        if(ObjectUtil.isNotEmpty(request)){
            HttpSession session = getSession(request);
            session.setAttribute(USER_NAME_IN_SESSION, user);
            return getUserFromSession(request);
        }else{
            return null;
        }

    }

    /**
     * 清除user
     * @param request
     * @return
     */
    public static boolean removeUserIntoSession(HttpServletRequest request){
        if(ObjectUtil.isNotEmpty(request)){
            HttpSession session = request.getSession();
            session.removeAttribute(USER_NAME_IN_SESSION);
        }
        return true;
    }

}
